package club.framework.web.application.aspect;


import club.framework.web.application.sys.log.entity.Log;
import club.framework.web.application.sys.user.entity.User;
import club.framework.web.base.annotation.ApplicationLog;
import club.framework.web.base.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @date 2017/9/7.
 * @Email:sunmch@163.com
 * @author: 念梓
 * des:切面拦截用户的操作日志入库
 */
@Service
@Aspect
public class ApplicationLogAspect {


    private static final Logger logger = LogManager.getLogger(ApplicationLogAspect.class);

    @Resource
    private HttpServletRequest request;

    @After("@annotation(applicationLog)")
    public void after(JoinPoint pjp,ApplicationLog applicationLog) {
        logger.info("成功执行后拦截的方法: 当前线程： {}",Thread.currentThread().getName());
        String execLog = applicationLog.msg();
        if(StringUtils.isNotBlank(execLog)){

        }
    }


    private User getUser() {
        return (User) request.getSession().getAttribute(Constants.USER_INFO);
    }

    private String getIp(){
        return request.getHeader("x-forwarded-for") == null ? request.getRemoteAddr() : request.getHeader("x-forwarded-for");
    }

    private String getURI(){
        return request.getRequestURI();
    }

    private Log getLog(String execMsg){
        Date now = new Date();
        Log log = new Log();
        log.setUpdateTime(now);
        log.setCreateTime(now);
        log.setUrl(getURI());
        log.setIp(getIp());
        log.setMsg(execMsg);
        return log;
    }
}
